package com.client.ryt.task.http;


import com.client.ryt.basic.BaseException;
import com.client.ryt.basic.BaseParameters;
import com.client.ryt.basic.BaseRequest;
import com.client.ryt.basic.BaseResponse;
import com.client.ryt.utils.NetUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 接口请求类
 */
public class HttpManager {

    private static HttpManager connection;
   // public final static String SERVICE_HTTP_URL = "http://192.168.102.112/RongCard/index.php?s=/Admin/Api";
    public final static String SERVICE_HTTP_URL = "http://121.42.13.194/index.php?s=/Admin/Api";
    /**
     * 根据请求获取结果
     * @param request
     * @return JSONObject
     */
    public static JSONObject getResponseJson(BaseRequest request){

        String req = request.encodeRequestString();
        if(NetUtil.isNetworkAvailable()) {
            HttpClient client = new DefaultHttpClient();
            try {
                HttpParams httpParams = client.getParams();
                client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
                // 读取超时
                client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000    );
                HttpGet httpRequest = new HttpGet(SERVICE_HTTP_URL +"/"+ request.method() +"/" + request.encodeRequestString());
                HttpResponse response = client.execute(httpRequest);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    long total = entity.getContentLength();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int count = 0;
                    int length = -1;
                    while ((length = is.read(buf)) != -1) {
                        baos.write(buf, 0, length);
                        count += length;
                    }
                    String json = new String(baos.toByteArray());
                    try {
                        return  new JSONObject(json);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
        return   new BaseException("请求失败").asJson();
    }


    public static JSONObject get(BaseRequest request) throws BaseException {

        HttpURLConnection conn = null;
        try {
            URL url = new URL(SERVICE_HTTP_URL +"/"+ request.method() +"/" + request.encodeRequestString());
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("contentType", "utf-8");
            // conn.setDoOutput(true);
            // conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream dis = new ByteArrayOutputStream();
            int realRead = 0;
            byte[] buff = new byte[1024];
            while ((realRead = is.read(buff )) != -1)
            {
                dis.write(buff,0,realRead);
            }
            String data = new String(dis.toByteArray(), "UTF-8").trim();

            // System.out.println(data);
            if (dis != null) dis.close();
            if(conn!=null)
            {
                conn.disconnect();//断开连接---问题产生的原因了
            }
            return  new JSONObject(data);
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        } catch (JSONException e) {
            throw new BaseException(e.getMessage());
        }
    }


/*    public static JSONObject post(ZPostRequest request) throws WutongException {

        HttpClient client = new DefaultHttpClient();
        // 请求超时
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
        // 读取超时
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000    );
        //HttpPost httpPost = new HttpPost(SERVICE_HTTP_URL + "?" + request.encodeRequestString());
        HttpPost httpPost = new HttpPost(SERVICE_HTTP_URL+"?"+request.encodeRequestString());
        //httpPost.addHeader("charset", HTTP.UTF_8);
        //httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
        HttpResponse response = null;

        Map<String,Object> params = request.encodeRequestParams();
        if (params != null && params.size() > 0) {
            List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                nameValuepairs.add(new BasicNameValuePair(key, "" + params.get(key)));
            }
            try {
                //httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs, HTTP.UTF_8));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs));
                response = client.execute(httpPost);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new HttpException(e.getMessage());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                throw new HttpException(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                throw new WutongException(e.getMessage());
            } catch (RuntimeException e) {
                e.printStackTrace();
                throw new WutongException(e.getMessage());
            }
        } else {
            try {
                response = client.execute(httpPost);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
//                throw new HttpException(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                throw new WutongException(e.getMessage());
            }
        }

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            InputStream is = null;
            try {
                is = entity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
                throw new WutongException(e.getMessage());
            }
            long total = entity.getContentLength();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int count = 0;
            int length = -1;
            try {
                while ((length = is.read(buf)) != -1) {
                    baos.write(buf, 0, length);
                    count += length;
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new WutongException(e.getMessage());
            }
            String json = new String(baos.toByteArray());
            try {
                return  new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
                throw new JsonException(e.getMessage());
            }
        }
        return null;
    }

    */

    public static <T extends BaseRequest> T buildRequest(Class<T> clazz,BaseParameters parameters){
        T req = null;
        try {
            req = clazz.newInstance();
            req.setParameters(parameters);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return req;
    }


    public static <T extends BaseResponse> T buildResponse(Class<T> tClass,BaseRequest request){
        T res = null;
        try {
            Constructor con = null;
            try {
                 con = tClass.getDeclaredConstructor(JSONObject.class);
                 con.setAccessible(true);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            try {
                res =  (T)con.newInstance(HttpManager.getResponseJson(request));
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return res;
    }
}
